package rad.framework.seam;

import java.io.Serializable;

import rad.framework.lang.ExceptionUtil;
import rad.framework.validator.ValidationUtil;

import org.hibernate.validator.InvalidValue;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

/**
 * This class cleans up the error.xhtml file, because
 * org.jboss.seam.handledException is not always present and thus throws a red
 * herring exception.
 * 
 * @author boudyacho
 * 
 */
@Name("rad.framework.seam.currentException")
@Scope(ScopeType.EVENT)
@BypassInterceptors
public class CurrentException implements Serializable {
	private static final long serialVersionUID = 1L;

	public Throwable getException() {
		try {
			return (Throwable) Component
					.getInstance("org.jboss.seam.handledException");
		} catch (Throwable e) {
			e.printStackTrace();
			try {
				return (Throwable) Component
						.getInstance("org.jboss.seam.exception");
			} catch (Throwable e2) {
				e2.printStackTrace();
				return null;
			}
		}
	}

	public InvalidValue[] getInvalidValues() {
		Throwable e = getException();
		if (e != null) {
			e = ExceptionUtil.getRootCause(e);
			return ValidationUtil.getInvalidValues(e);
		}
		return new InvalidValue[0];
	}

	/**
	 * Used for testing.
	 */
	public void simulate() {
		throw new RuntimeException("Test Exception");
	}
}
